home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 107 < prev    next >
Internet Message Format  |  1996-08-06  |  2KB

  1. Path: stingray.mcnc.org!coats
  2. From: coats@mcnc.org (Carlie Coats)
  3. Newsgroups: comp.std.c
  4. Subject: Re: Help, best way to compare doubles
  5. Date: 15 Jan 1996 11:48:52 GMT
  6. Organization: MCNC, RTP, NC
  7. Message-ID: <4ddev4$1vg@stingray.mcnc.org>
  8. References: <4d1k09$aqq@mercury.IntNet.net> <4dbos6$o7q@umbc9.umbc.edu>
  9. NNTP-Posting-Host: robin.mcnc.org
  10.  
  11. In article <4dbos6$o7q@umbc9.umbc.edu>,
  12. Jonas J. Schlein <schlein@umbc.edu> wrote:
  13. >Jeff Tomich <jtomich@IntNet.net> wrote:
  14. >|> Having a hard time to figure out a function on how to compare doubles. 
  15. >|> Any ideas?
  16. >
  17. >I'd go along with what the c.l.c. FAQ has to say about this one:
  18. >
  19. >14.5:    What's a good way to check for "close enough" floating-point
  20. >    equality?
  21. >
  22. >A:    Since the absolute accuracy of floating point values varies, by
  23. >    definition, with their magnitude, the best way of comparing two
  24. >    floating point values is to use an accuracy threshold which is
  25. >    relative to the magnitude of the numbers being compared.  Rather
  26. >    than
  27. >
  28. >        double a, b;
  29. >        ...
  30. >        if(a == b)    /* WRONG */
  31. >
  32. >    use something like
  33. >
  34. >        #include <math.h>
  35. >
  36. >        if(fabs(a - b) <= epsilon * a)
  37. >
  38. >    for some suitably-chosen epsilon.
  39. >
  40. >    References: Knuth Sec. 4.2.2 pp. 217-8.
  41.  
  42. As stated, this is dangerous.  Perhaps the FAQ needs revision.
  43.  
  44. Knuth is careful to put absolute value signs on both sides.
  45. For once, he is not careful to consider the case that a is
  46. zero.  A safer test is of the form
  47.  
  48.     | a - b | / sqrt( a^2 + b^2 + delta ) < epsilon
  49.  
  50. or (equvalently, but in decently-efficient C):
  51.  
  52.     ( t = a - b )*t < esquared * ( a*a + b*b  + delta )
  53.  
  54. The choice of esquared == delta == 1e-20  gives this a
  55. colloquial English meaning of 
  56.  
  57.     "a and b agree to about 10 significant digits"
  58.  
  59. which is a reasonable version of "are approximately equal"
  60. for doubles.
  61.  
  62.  
  63. Carlie J. Coats, Jr.              coats@ncsc.org    *or*    xcc@hpcc.epa.gov
  64. MCNC Environmental Programs                             phone: (919)248-9241
  65. North Carolina Supercomputing Center                      fax: (919)248-9245
  66. 3021 Cornwallis Road                                         P. O. Box 12889
  67. Research Triangle Park, N. C.  27709-2889                                USA
  68. "My opinions are my own, and I've got *lots* of them!"
  69.  
  70.